package cn.com.callback

import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHUtil
import cn.com.kh.LogToDB
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.ParseException
import java.text.SimpleDateFormat

/**
 *
 * @Title: waterOffFax* @Description:智慧停水 传真数据同步接口--外部接口
 * @author: cheih* @date 2021-12-22 10:28:00
 *
 */

public class waterOffFax implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(waterOffFax.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);
        long startTime = System.currentTimeMillis();

        String inData = "";
        String outData = "";
        String dataSourceID = "dataSource";
        String wateroffplantype = "";

        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }

        try {
            // 调用处理信息
            JSONObject inObject = new JSONObject(inData);
            log.debug("处理前的Json：" + inObject.toString());
            def timestamp = KHUtil.GetJV(inObject, "timestamp");//时间戳
            def sign = KHUtil.GetJV(inObject, "sign");//密钥

            log.debug("解析信息-" + " timestamp: " + timestamp + " sign: " + sign);
            String reJson = null;
            long endTime = 0;

            String apiid = "waterOff";
            String apikey = "55bd38420d354822bdb789284fac4ab3";

            String signfront = "apiid" + "=" + apiid + "&" + "apikey" + "=" + apikey + "&" + "timestamp" + "=" + timestamp;
            log.debug("sign加密MD5前：" + signfront);
            String signafter = Util.getMD5Str(signfront);
            log.debug("sign加密MD5后：" + signafter);

            if (!sign.equals(signafter)) {
                log.debug("signafter不存在");
                endTime = System.currentTimeMillis();
                outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(sign签名错误),调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
            } else {

                wateroffplantype = KHUtil.GetJV(inObject, "wateroffplantype");// normal 正常 change 改期 delay 延期

                if (wateroffplantype == "change") {
                    // 改期（原停水编号，类型，取消原因） 改期仅需要关闭现有批次即可 综合调度系统会重新推送批次
                    String wateroffoldsmsguid = KHUtil.GetJV(inObject, "wateroffoldsmsguid");
                    String wateroffchangetype = KHUtil.GetJV(inObject, "wateroffchangetype");
                    String wateroffchangereason = KHUtil.GetJV(inObject, "wateroffchangereason");
                    String url_data = KHUtil.GetJV(inObject, "data");//传真文件地址

                    //非空校验
                    String dealMessage = KHUtil.isNullMSG("wateroffoldsmsguid", wateroffoldsmsguid) + KHUtil.isNullMSG("wateroffchangetype", wateroffchangetype) + KHUtil.isNullMSG("wateroffchangereason", wateroffchangereason) + KHUtil.isNullMSG("url_data", url_data);

                    if (!KHUtil.isNull(dealMessage)) {
                        endTime = System.currentTimeMillis();
                        outData = "{\"resultcode\":\"0\",\"resultmessage\":\"改期调用参数非空校验异常:" + dealMessage + "，调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
                    } else {
                        log.debug("入参：wateroffoldsmsguid" + wateroffoldsmsguid + ",	wateroffchangetype:" + wateroffchangetype + ",	wateroffchangereason:" + wateroffchangereason);
                        //新增SMS
                        outData = changeFAX(eliteBean, wateroffoldsmsguid, wateroffchangetype, wateroffchangereason, url_data);
                    }

                } else if (wateroffplantype == "delay") {
                    // 延期（原停水编号，延期后供水日期，延期原因）
                    String wateroffoldsmsguid = KHUtil.GetJV(inObject, "wateroffoldsmsguid");
                    String wateroffdelaytime = KHUtil.GetJV(inObject, "wateroffdelaytime");
                    String wateroffdelayreason = KHUtil.GetJV(inObject, "wateroffdelayreason");
                    String url_data = KHUtil.GetJV(inObject, "data");//传真文件地址

                    //非空校验
                    String dealMessage = KHUtil.isNullMSG("wateroffoldsmsguid", wateroffoldsmsguid) + KHUtil.isNullMSG("wateroffdelaytime", wateroffdelaytime) + KHUtil.isNullMSG("wateroffdelayreason", wateroffdelayreason) + KHUtil.isNullMSG("url_data", url_data);

                    if (!KHUtil.isNull(dealMessage)) {
                        endTime = System.currentTimeMillis();
                        outData = "{\"resultcode\":\"0\",\"resultmessage\":\"延期调用参数非空校验异常:" + dealMessage + "，调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
                    } else {
                        log.debug("入参：wateroffoldsmsguid" + wateroffoldsmsguid + ",	wateroffdelaytime:" + wateroffdelaytime + ",	wateroffdelayreason:" + wateroffdelayreason);
                        //新增SMS
                        outData = delayFAX(eliteBean, wateroffoldsmsguid, wateroffdelaytime, wateroffdelayreason, url_data);
                    }

                } else {

                    String wateroffsmsguid = KHUtil.GetJV(inObject, "wateroffsmsguid");//停水批次编号
                    String wateroffoldsmsguid = KHUtil.GetJV(inObject, "wateroffoldsmsguid");//原停水批次编号
                    String wateroffsmsname = KHUtil.GetJV(inObject, "wateroffsmsname");//停水批次名称
                    String cutoffwater = KHUtil.GetJV(inObject, "cutoffwater");//停水原因
                    String waterofftime = KHUtil.GetJV(inObject, "waterofftime");//关阀时间
                    String waterontime = KHUtil.GetJV(inObject, "waterontime");//恢复通水时间
                    String url_data = KHUtil.GetJV(inObject, "data1");//传真文件地址
                    String company_data = KHUtil.GetJV(inObject, "data2");//发送单位
                    String url = KHUtil.GetJV(inObject, "url");//单独传url说明也是改期

                    log.debug("处理前入参wateroffsmsguid:" + wateroffsmsguid + " wateroffplantype:" + wateroffplantype + " url:" + url + " url_data:" + url_data + " company_data:" + company_data);

                    // 判断是否是取消
                    if (KHUtil.isNull(wateroffplantype) && (!KHUtil.isNull(url) || (!KHUtil.isNull(url_data) && url_data != "[]")) && (KHUtil.isNull(company_data) || company_data == "[]")) {
                        log.debug("处理前url:" + url + " url_data:" + url_data);
                        url = KHUtil.isNull(url) ? url_data : url;
                        log.debug("非空判断后url:" + url + " url_data:" + url_data);
                        url = url.startsWith("[") ? url : "[{\"url\":\"" + url + "\"}]";
                        log.debug("数组加工处理后url:" + url + " url_data:" + url_data);

                        wateroffplantype == "cancel";

                        //非空校验
                        String dealMessage = KHUtil.isNullMSG("wateroffsmsguid", wateroffsmsguid) + KHUtil.isNullMSG("wateroffsmsname", wateroffsmsname) + KHUtil.isNullMSG("url", url);
                        if (!KHUtil.isNull(dealMessage)) {
                            endTime = System.currentTimeMillis();
                            outData = "{\"resultcode\":\"0\",\"resultmessage\":\"取消调用参数非空校验异常:" + dealMessage + "，调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";

                        } else {
                            log.debug("入参：wateroffsmsguid" + wateroffsmsguid + ",	wateroffsmsname:" + wateroffsmsname + ", waterofftime:" + waterofftime + ",	waterontime:" + waterontime + ",	url_data:" + url_data + ",	company_data:" + company_data + ", url:" + url);
                            //新增SMS
                            outData = FAXcancel(eliteBean, wateroffsmsguid, wateroffsmsname, cutoffwater, url);

                        }
                    } else {
                        wateroffplantype = "add";

                        //非空校验
                        String dealMessage = KHUtil.isNullMSG("wateroffsmsguid", wateroffsmsguid) + KHUtil.isNullMSG("wateroffsmsname", wateroffsmsname) + KHUtil.isNullMSG("cutoffwater", cutoffwater) + KHUtil.isNullMSG("waterofftime", waterofftime) + KHUtil.isNullMSG("waterontime", waterontime) + KHUtil.isNullMSG("data1", url_data) + KHUtil.isNullMSG("data2", company_data);
                        if (!KHUtil.isNull(dealMessage)) {
                            endTime = System.currentTimeMillis();
                            outData = "{\"resultcode\":\"0\",\"resultmessage\":\"新增调用参数非空校验异常:" + dealMessage + "，调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";

                        } else {
                            log.debug("入参：wateroffsmsguid" + wateroffsmsguid + ",	wateroffsmsname:" + wateroffsmsname + ",	waterofftime:" + waterofftime + ",	waterontime:" + waterontime + ",	url_data:" + url_data + ",	company_data:" + company_data);
                            //新增SMS
                            outData = FAXAdd(eliteBean, wateroffsmsguid, wateroffsmsname, waterofftime, waterontime, cutoffwater, url_data, company_data, wateroffoldsmsguid);

                        }
                    }
                }
            }

        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "智慧停水[传真]", "waterOffFax", inData, outData, (System.currentTimeMillis() - startTime).toString(), wateroffplantype);
        }

        log.debug("传真数据接入处理完成返回结果:" + outData);

        return outData;
    }

    // 传真处理
    public static String FAXAdd(EliteBean eliteBean, String wateroffsmsguid, String wateroffsmsname, String waterofftime, String waterontime, String cutoffwater, String urlinJson, String companyinJson, String wateroffoldsmsguid) {

        long startTime = System.currentTimeMillis();
        log.debug("传真处理开始时间:" + startTime);

        long endTime = System.currentTimeMillis();

        String reJson = null;
        try {
            //查询现有当前传真批次是否存在
            List getSelectSQL = eliteBean.chaxun_sql("select count(*) as count from waterOffFaxbatch where 1=1 and status!=2 and wateroffsmsguid= '" + wateroffsmsguid + "' ", "dataSource");
            int count = 0;
            if (getSelectSQL.size() > 0) {
                count = getSelectSQL.get(0).get("count");
                if (count > 0) {//存在则废弃之前的批次
                    String[] abandondata = new String[2];
                    //将还未发送成功的批次更新为废弃
                    abandondata[0] = "update waterOffFaxbatch set status=3,suspenddate=GETDATE() where 1=1 and status!=2 and  wateroffsmsguid=  '" + wateroffsmsguid + "'";
                    //废弃还未同步的传真任务
                    abandondata[1] = "update Kh_Sw_Sendfax set status=2 where 1=1 and status=0 and wateroffsmsguid= '" + wateroffsmsguid + "'";

                    log.debug("当前传真批次已经存在执行结果SQL:" + abandondata.toString());
                    def abandondataresult = eliteBean.updateBatch(abandondata, "dataSource");
                    log.debug("当前传真批次已经存在执行结果SQL结果:" + abandondataresult.toString());

                }
            }
            String sms_guid = UUID.randomUUID().toString();

            JSONArray arrJsonArray = new JSONArray(companyinJson);
            int arrInt = arrJsonArray.length();
            log.debug("接入List数量:" + arrInt);

            if (arrInt > 0) {
                eliteBean.update("Update Waterofffaxbatch Set Ismain = 0 Where Wateroffsmsguid = '" + wateroffsmsguid + "'", "dataSource");
                int batchresult = eliteBean.update("INSERT INTO waterOffFaxbatch(wateroffsmsguid, wateroffsmsname, waterofftime, waterontime, createdate,sms_guid,status,cutoffwater,fileurl,wateroffoldsmsguid,ismain) VALUES ('" + wateroffsmsguid + "', '" + wateroffsmsname + "',  '" + waterofftime + "','" + waterontime + "',GETDATE(),'" + sms_guid + "',0,'" + cutoffwater + "','" + urlinJson + "','" + wateroffoldsmsguid + "',1)", "dataSource");
                log.debug("当前批次新建结果SQL结果:" + batchresult.toString());
            } else {
                log.debug("当前批次无需发送类型是取消通知");
            }

            JSONArray resArray = new JSONArray();
            Map<String, String> dealMap = new HashMap<String, String>();
            Map<String, String> dealMsgMap = new HashMap<String, String>();

            for (int i = 0; i < arrInt; i++) {

                JSONObject arrSmsJson = arrJsonArray.getJSONObject(i);
                String companyname = KHUtil.GetJV(arrSmsJson, "companyname"); //传真通知单位
                String companymobile = KHUtil.GetJV(arrSmsJson, "companymobile"); //传真号码

                String dealResult = "";
                String dealMessage = "";

                //处理结果字段dealResult 1成功 其他失败S
                if (KHUtil.isNull(companymobile)) {
                    dealMessage = KHUtil.isNullMSG("companymobile", companymobile);
                    endTime = System.currentTimeMillis();
                    log.warn(dealMessage);
                    reJson = "{\"resultcode\":\"3\",\"resultmessage\":\"处理失败(" + dealMessage + "),调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
                    return reJson;
                } else {
                    try {//停水通知传真提前24小时发送，这里需要微调一下，超过晚上9点就不能发了，设置为提前（21:00）发送
                        companymobile = companymobile.replace("-", "");

                        //转换时间获取时分秒
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String str = waterofftime;
                        Date d = formatter.parse(str);
                        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
                        String date = format.format(d);
                        log.debug("获得时分秒date：" + date);

                        String[] data = new String[2];
                        data[0] = "Insert Into Kh_Sw_Sendfax(Rec_Guid,sms_guid,wateroffsmsguid,Subject,Faxnumber,Faxnumberext,Rawfile,Firstpage,Lastpage,Qr,Status,Expectedstartdate) Values(newid(),'" + sms_guid + "','" + wateroffsmsguid + "','" + wateroffsmsname + "', '" + companymobile + "', '', '" + urlinJson + "', '', '', '{}', 0, GETDATE())";
                        data[1] = "update waterOffFaxbatch set count=count+1 where wateroffsmsguid=  '" + wateroffsmsguid + "' and sms_guid='" + sms_guid + "'";

                        log.debug("当前传真号码执行insert结果SQL:" + data.toString());

                        int[] dataresult = eliteBean.updateBatch(data, "dataSource");
                        log.debug("当前传真号码执行insert结果SQL结果:" + dataresult.toString());

                        dealResult = "1";
                        log.debug("当前传真号码insert执行结果，dataresult:" + dataresult);
                    } catch (Exception e) {
                        dealResult = "0";
                        dealMessage = "当前传真号码insert执行更新结果SQL异常";
                        log.error(dealMessage + ":" + e.getMessage());
                    }
                    log.debug("当前传真号码ID:" + companymobile + " 处理结果Code:" + dealResult + " 处理结果Message:" + dealMessage);
                    dealMap.put(companymobile, dealResult);
                    dealMsgMap.put(companymobile, dealMessage);
                }
            }

            // 将每条处理结果转换为JSONArray
            int j = 0;
            for (Map.Entry<String, String> m : dealMap.entrySet()) {
                JSONObject resObject = new JSONObject();
                resObject.put("companymobile", m.getKey());
                resObject.put("code", m.getValue());
                resObject.put("message", dealMsgMap.get(m.getKey()).toString());
                resArray.put(j, resObject);
                j++;
            }

            int statusresult = eliteBean.update("update waterOffFaxbatch set status=1,modifydate=GETDATE() where wateroffsmsguid=  '" + wateroffsmsguid + "' and sms_guid='" + sms_guid + "'", "dataSource");
            log.debug("当前批次同步完成	status更新:" + statusresult.toString());

            //生成处理完成时间
            endTime = System.currentTimeMillis();

            // 包装拼接返回JSONObject
            reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"批次号:" + wateroffsmsguid + ",批次名称：" + wateroffsmsname + "处理完成,调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":" + resArray.toString() + "}";


        } catch (JSONException e) {
            endTime = System.currentTimeMillis();
            reJson = "{\"resultcode\":\"4\",\"resultmessage\":\"批次号:" + wateroffsmsguid + ",批次名称：" + wateroffsmsname + "处理失败(" + e.getMessage() + "),调用处理时长(毫秒):" + (endTime - startTime) + "\"}";
        }

        return reJson;
    }

    // 传真改期处理
    public static String changeFAX(EliteBean eliteBean, String wateroffsmsguid, String wateroffchangetype, String wateroffchangereason, String urlinJson) {

        long startTime = System.currentTimeMillis();
        log.debug("传真改期处理开始时间:" + startTime);

        String Sms_Guid = UUID.randomUUID().toString();

        String reJson = null;
        try {
            //查询现有当前传真批次是否存在
            List getSelectSQL = eliteBean.chaxun_sql("Select Sms_Guid From Waterofffaxbatch Where Wateroffsmsguid = '" + wateroffsmsguid + "' And Ismain = 1", "dataSource");
            if (getSelectSQL.size() > 0) {

                String old_Sms_Guid = getSelectSQL.get(0).get("Sms_Guid");

                String[] abandondata = new String[4];
                // 将批次改为改期
                abandondata[0] = '''Update Waterofffaxbatch
                                       Set Status       = 5,
                                           Ismain       = 0,
                                           Suspenddate  = Getdate(),
                                           Changetype   = \'''' + wateroffchangetype + '''\',
                                           Changereason = \'''' + wateroffchangereason + '''\'
                                     Where Sms_Guid = \'''' + old_Sms_Guid + '''\'''';

                // 废弃还未同步的传真任务
                abandondata[1] = '''Update Kh_Sw_Sendfax
                                           Set Status = -5
                                         Where Status = 0
                                           And Sms_Guid = \'''' + old_Sms_Guid + '''\'''';
                // 新生成主任务
                abandondata[2] = '''Insert Into Waterofffaxbatch
                                          (Wateroffsmsguid,
                                           Wateroffsmsname,
                                           Waterofftime,
                                           Waterontime,
                                           Createdate,
                                           Sms_Guid,
                                           Status,
                                           Cutoffwater,
                                           Fileurl,
                                           Wateroffoldsmsguid, Ismain, Count)
                                          Select Wateroffsmsguid,
                                                 Wateroffsmsname,
                                                 Waterofftime,
                                                 Waterontime,
                                                 Getdate(),
                                                 \'''' + Sms_Guid + '''\',
                                                 1,
                                                 Cutoffwater,
                                                 \'''' + urlinJson + '''\',
                                                 Wateroffoldsmsguid, 1, Count
                                            From Waterofffaxbatch
                                           Where Sms_Guid = \'''' + old_Sms_Guid + '''\'''';

                abandondata[3] = '''Insert Into Kh_Sw_Sendfax
                                          (Rec_Guid,
                                           Sms_Guid,
                                           Wateroffsmsguid,
                                           Subject,
                                           Faxnumber,
                                           Faxnumberext,
                                           Rawfile,
                                           Firstpage,
                                           Lastpage,
                                           Qr,
                                           Status,
                                           Expectedstartdate)
                                          Select Newid(),* From (Select Distinct
                                                 \'''' + Sms_Guid + '''\' As Sms_Guid,
                                                 \'''' + wateroffsmsguid + '''\' AS wateroffsmsguid,
                                                 Subject,
                                                 Faxnumber,
                                                 Faxnumberext,
                                                 \'''' + urlinJson + '''\' AS urlinJson,
                                                 Firstpage,
                                                 Lastpage,
                                                 '{}' AS Qr,
                                                 0 AS Status,
                                                 Getdate() AS Expectedstartdate
                                            From Kh_Sw_Sendfax
                                           Where Sms_Guid = \'''' + old_Sms_Guid + '''\') R1''';

                log.debug("当前传真批次已经存在执行结果SQL:" + abandondata.toString());
                int[] abandondataresult = eliteBean.updateBatch(abandondata, "dataSource");
                log.debug("当前传真批次已经存在执行结果SQL结果:" + abandondataresult.toString());

                // 包装拼接返回JSONObject
                reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"批次号:" + wateroffsmsguid + " 改期处理完成,调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\"}";
            } else {
                // 包装拼接返回JSONObject
                reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"批次号:" + wateroffsmsguid + " 改期处理失败,当前批次CRM不存在,调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\"}";
            }

        } catch (JSONException e) {
            reJson = "{\"resultcode\":\"4\",\"resultmessage\":\"批次号:" + wateroffsmsguid + " 改期处理异常(" + e.getMessage() + "),调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\"}";
        }

        return reJson;
    }

    // 传真延期处理
    public static String delayFAX(EliteBean eliteBean, String wateroffsmsguid, String wateroffdelaytime, String wateroffdelayreason, String urlinJson) {

        long startTime = System.currentTimeMillis();
        log.debug("传真延期处理开始时间:" + startTime);

        String Sms_Guid = UUID.randomUUID().toString();

        String reJson = null;
        try {
            //查询现有当前传真批次是否存在
            List getSelectSQL = eliteBean.chaxun_sql("Select Sms_Guid From Waterofffaxbatch Where Wateroffsmsguid = '" + wateroffsmsguid + "' And Ismain = 1", "dataSource");
            if (getSelectSQL.size() > 0) {
                String old_Sms_Guid = getSelectSQL.get(0).get("Sms_Guid");

                String[] abandondata = new String[4];
                //将还未发送成功的批次更新为废弃
                abandondata[0] = '''Update Waterofffaxbatch
                                       Set Status      = 6,
                                           Ismain       = 0,
                                           Suspenddate = Getdate(),
                                           Delaytime   = \'''' + wateroffdelaytime + '''\',
                                           Delayreason = \'''' + wateroffdelayreason + '''\'
                                     Where Sms_Guid = \'''' + old_Sms_Guid + '''\'''';

                // 废弃还未同步的传真任务
                abandondata[1] = '''Update Kh_Sw_Sendfax
                                           Set Status = -6
                                         Where Status = 0
                                           And Sms_Guid = \'''' + old_Sms_Guid + '''\'''';
                // 新生成主任务
                abandondata[2] = '''Insert Into Waterofffaxbatch
                                          (Wateroffsmsguid,
                                           Wateroffsmsname,
                                           Waterofftime,
                                           Waterontime,
                                           Createdate,
                                           Sms_Guid,
                                           Status,
                                           Cutoffwater,
                                           Fileurl,
                                           Wateroffoldsmsguid, Ismain, Count)
                                          Select Wateroffsmsguid,
                                                 Wateroffsmsname,
                                                 Waterofftime,
                                                 Waterontime,
                                                 Getdate(),
                                                 \'''' + Sms_Guid + '''\',
                                                 1,
                                                 Cutoffwater,
                                                 \'''' + urlinJson + '''\',
                                                 Wateroffoldsmsguid, 1, Count
                                            From Waterofffaxbatch
                                           Where Sms_Guid = \'''' + old_Sms_Guid + '''\'''';

                abandondata[3] = '''Insert Into Kh_Sw_Sendfax
                                          (Rec_Guid,
                                           Sms_Guid,
                                           Wateroffsmsguid,
                                           Subject,
                                           Faxnumber,
                                           Faxnumberext,
                                           Rawfile,
                                           Firstpage,
                                           Lastpage,
                                           Qr,
                                           Status,
                                           Expectedstartdate)
                                          Select Newid(),* From (Select Distinct
                                                 \'''' + Sms_Guid + '''\' As Sms_Guid,
                                                 \'''' + wateroffsmsguid + '''\' AS wateroffsmsguid,
                                                 Subject,
                                                 Faxnumber,
                                                 Faxnumberext,
                                                 \'''' + urlinJson + '''\' AS urlinJson,
                                                 Firstpage,
                                                 Lastpage,
                                                 '{}' AS Qr,
                                                 0 AS Status,
                                                 Getdate() AS Expectedstartdate
                                            From Kh_Sw_Sendfax
                                           Where Sms_Guid = \'''' + old_Sms_Guid + '''\') R1''';

                log.debug("当前传真批次已经存在执行结果SQL:" + abandondata.toString());
                int[] abandondataresult = eliteBean.updateBatch(abandondata, "dataSource");
                log.debug("当前传真批次已经存在执行结果SQL结果:" + abandondataresult.toString());

                // 包装拼接返回JSONObject
                reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"批次号:" + wateroffsmsguid + " 延期处理完成,调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\"}";
            } else {
                // 包装拼接返回JSONObject
                reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"批次号:" + wateroffsmsguid + " 延期处理失败,当前批次CRM不存在,调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\"}";
            }

        } catch (Exception e) {
            reJson = "{\"resultcode\":\"4\",\"resultmessage\":\"批次号:" + wateroffsmsguid + " 延期处理异常(" + e.getMessage() + "),调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\"}";
        }

        return reJson;
    }

    // 传真取消处理-4
    public static String FAXcancel(EliteBean eliteBean, String wateroffsmsguid, String wateroffsmsname, String cutoffwater, String urlinJson) {

        long startTime = System.currentTimeMillis();
        log.debug("传真取消处理开始时间:" + startTime);

        String Sms_Guid = UUID.randomUUID().toString();

        String reJson = null;
        try {
            //查询现有当前传真批次是否存在
            List getSelectSQL = eliteBean.chaxun_sql("Select Sms_Guid From Waterofffaxbatch Where Wateroffsmsguid = '" + wateroffsmsguid + "' And Ismain = 1", "dataSource");
            if (getSelectSQL.size() > 0) {
                String old_Sms_Guid = getSelectSQL.get(0).get("Sms_Guid");

                String[] abandondata = new String[4];
                //将还未发送成功的批次更新为废弃
                abandondata[0] = '''Update Waterofffaxbatch
                                       Set Status      = 4,
                                           Ismain       = 0,
                                           Suspenddate = Getdate(),
                                           Canceltime   = Getdate(),
                                           Cancelreason = \'''' + cutoffwater + '''\'
                                     Where Sms_Guid = \'''' + old_Sms_Guid + '''\'''';

                // 废弃还未同步的传真任务
                abandondata[1] = '''Update Kh_Sw_Sendfax
                                           Set Status = -4
                                         Where Status = 0
                                           And Sms_Guid = \'''' + old_Sms_Guid + '''\'''';
                // 新生成主任务
                abandondata[2] = '''Insert Into Waterofffaxbatch
                                          (Wateroffsmsguid,
                                           Wateroffsmsname,
                                           Waterofftime,
                                           Waterontime,
                                           Createdate,
                                           Sms_Guid,
                                           Status,
                                           Cutoffwater,
                                           Fileurl,
                                           Wateroffoldsmsguid, Ismain, Count)
                                          Select Wateroffsmsguid,
                                                 Wateroffsmsname,
                                                 Waterofftime,
                                                 Waterontime,
                                                 Getdate(),
                                                 \'''' + Sms_Guid + '''\',
                                                 1,
                                                 Cutoffwater,
                                                 \'''' + urlinJson + '''\',
                                                 Wateroffoldsmsguid, 1, Count
                                            From Waterofffaxbatch
                                           Where Sms_Guid = \'''' + old_Sms_Guid + '''\'''';

                abandondata[3] = '''Insert Into Kh_Sw_Sendfax
                                          (Rec_Guid,
                                           Sms_Guid,
                                           Wateroffsmsguid,
                                           Subject,
                                           Faxnumber,
                                           Faxnumberext,
                                           Rawfile,
                                           Firstpage,
                                           Lastpage,
                                           Qr,
                                           Status,
                                           Expectedstartdate)
                                          Select Newid(),* From (Select Distinct
                                                 \'''' + Sms_Guid + '''\' As Sms_Guid,
                                                 \'''' + wateroffsmsguid + '''\' As wateroffsmsguid,
                                                 Subject,
                                                 Faxnumber,
                                                 Faxnumberext,
                                                 \'''' + urlinJson + '''\' As Rawfile,
                                                 Firstpage,
                                                 Lastpage,
                                                 '{}' As Qr,
                                                 0 As Status,
                                                 Getdate() As Expectedstartdate
                                            From Kh_Sw_Sendfax
                                           Where Sms_Guid = \'''' + old_Sms_Guid + '''\') R1''';

                log.debug("当前传真批次已经存在执行结果SQL:" + abandondata.toString());
                int[] abandondataresult = eliteBean.updateBatch(abandondata, "dataSource");
                log.debug("当前传真批次已经存在执行结果SQL结果:" + abandondataresult.toString());


                // 包装拼接返回JSONObject
                reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"批次号:" + wateroffsmsguid + " 处理完成,当前批次CRM取消成功,调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\"}";
            } else {
                // 包装拼接返回JSONObject
                reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"批次号:" + wateroffsmsguid + " 取消处理失败,当前批次CRM不存在,调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\"}";
            }

        } catch (Exception e) {
            reJson = "{\"resultcode\":\"4\",\"resultmessage\":\"批次号:" + wateroffsmsguid + " 取消处理异常(" + e.getMessage() + "),调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\"}";
        }

        return reJson;
    }

}
